﻿using System;
using System.Data;
using System.IO;
using System.Linq;
using CommonFunction;
using QualityApp;

namespace ClearCustomerInvoiceOutData
{
    /*
     * 2018-1-16 转普票有正负数在一张销货单上的情况
     * 2015-10-23 修正转普票程序，里的转票表金额使用求和过程中的最小值
     * 2015-6-17 转普票程序
     */
    class Program
    {
        private static void Main(string[] args)
        {
            WriteLog log = new WriteLog();

            string cfgINI = AppDomain.CurrentDomain.BaseDirectory + @"\user.ini";
            //GetEncodeDBdata();
            if (File.Exists(cfgINI))
            {
                IniFile ini = new IniFile(cfgINI);

                DataProvider.ConnectString = ini.IniReadValue("DataSource", "DB");
                GetCustomerInvoiceOutData();
                log.WriteLogs("OK"); 
            }
            else
            {
                log.WriteLogs("Error:缺少数据库配置文件"); 
            }
        }
        private static void GetCustomerInvoiceOutData()
        {
            try
            {
                //获取到要转普票的数据
                DataTable dtOutData3 = DataProvider.Instance.GetTable("exec [usp_GetCustomerInvoiceOutData33]", "");

                if (dtOutData3 == null || dtOutData3.Rows.Count <= 0) return; //没有要转普票的则不进行

                foreach (DataRow drOutData in dtOutData3.Rows)
                {
                    if (drOutData["isid"] is DBNull) continue;
                    if (drOutData["isid"] == null) continue;
                    if (drOutData["InvoiceOutAmount"] is DBNull) continue;
                    if (drOutData["InvoiceOutAmount"] == null) continue;

                    int isid = Convert.ToInt32(drOutData["isid"]);
                    //此条记录的开票金额
                    decimal invoiceOutAmount = Convert.ToDecimal(drOutData["InvoiceOutAmount"]);

                    string cusCode = Convert.ToString(drOutData["CusCode"]);
                    string artNo = Convert.ToString(drOutData["ArtNo"]);
                    //获取该规格所属货物分组
                    string sql = "select top 1 ISNULL(GroupCode,'') from T_ProductGroupRe where ArtNo='" + artNo + "'";
                    object objGroupCode = DataProvider.Instance.ExecuteScalar(sql);
                    string proGroupCode = Convert.ToString(objGroupCode);

                    DataTable dtUnInvoicedData = GetCustomerUnInvoicedData(cusCode, proGroupCode);
                    if (dtUnInvoicedData == null || dtUnInvoicedData.Rows.Count <= 0) continue;

                    DataView dvUnInvoicedData = dtUnInvoicedData.DefaultView;
                    dvUnInvoicedData.Sort = "isid";
                    //排序后的数据表排序
                    dtUnInvoicedData = dvUnInvoicedData.Table;

                    //在未开票明细里的没有匹配到该isid的条目，或者多余1，不进行转普票操作
                    if (dtUnInvoicedData.Select("isid=" + isid).Length != 1) continue;

                    var qUnInvoicedData = dtUnInvoicedData.AsEnumerable();

                    //得到最后一笔负数的isid的值
                    int maxIsid = -1;
                    var q1 = from r in qUnInvoicedData
                        where Convert.ToDecimal(r["InvoiceOutAmount"]) < 0
                              && r.Field<int>("isid") > isid
                        select r;

                    maxIsid = q1.Any() ? q1.Max(r => r.Field<int>("isid")) : isid;

                    //小于等于isid的值金额和
                    decimal sumAmountIsidPre = (from r in qUnInvoicedData
                        where r.Field<int>("isid") <= isid
                        select r.Field<decimal>("InvoiceOutAmount")).Sum();

                    //前半部分金额合计小于等于0，那么该笔明细不能转普票
                    if (sumAmountIsidPre <= 0) continue;
                    
                    //转普票的实际金额 2018-7-17 q2可能为空，此处需要检测合计金额大小，防止转普票金额过大
                    if (invoiceOutAmount > sumAmountIsidPre) invoiceOutAmount = sumAmountIsidPre;

                    //后半部分的金额
                    var q2 = from r in qUnInvoicedData
                        where r.Field<int>("isid") > isid
                              && r.Field<int>("isid") <= maxIsid
                        select r;

                    foreach (DataRow row2 in q2)
                    {
                        if (row2["InvoiceOutAmount"] is DBNull || row2["InvoiceOutAmount"] == null) continue;

                        sumAmountIsidPre += Convert.ToDecimal(row2["InvoiceOutAmount"]);

                        //2015-10-23 只取求和时的最小值。转普票的实际金额
                        if (invoiceOutAmount > sumAmountIsidPre) invoiceOutAmount = sumAmountIsidPre;
                        //金额小于等于0 那么此条不能转普票
                        if (sumAmountIsidPre <= 0) break;
                    }
                    
                    //负数不转普票,2015-8-17 为0 也不转普票
                    if(invoiceOutAmount<=0) continue;
                    
                    //执行转普票
                    string strSql = "exec [usp_ClearCustomerInvoiceOutData2] " + isid + "," + invoiceOutAmount + ",'" + cusCode + "'";
                    DataProvider.Instance.ExecuteNoQuery(strSql);

                    WriteLog log = new WriteLog();
                    log.WriteLogs("1成功:" + strSql);
                }
            }
            catch (Exception err)
            {
                WriteLog log= new WriteLog();
                log.WriteLogs(err.Message);
            }
        }
        private static DataTable GetCustomerUnInvoicedData(string cusCode, string proGroupCode)
        {
            return DataProvider.Instance.GetTable("exec [usp_GetCustomerUnInvoicedData] '" + cusCode + "','','" + proGroupCode + "'", "");
        }
    }
}
